import React, { useEffect, useRef, useState,forwardRef, useImperativeHandle}  from "react";
import { withRouter } from "react-router-dom";
import commonConfig from 'static/js/commonConfig'
import { connect } from 'react-redux'
import {AddOrModifyThemeCourses,getThemeByIdPublish,SubjectApprovalCourse,setRemark,getThemeById} from 'api/index'
import {notification, Modal,Tabs,Form,Select,Spin,Alert, message} from 'antd'
import {checkDraftData} from 'redux/action'
import LlxForm from 'components/LlxForm'
import  UploadPicture  from 'components/Upload/index'
// 查看更多弹框
import LookMore from 'components/Operations/LookMore'
import LlxHead from "components/Operations/LlxHead";
import AfterQuestions from "components/PageCommon/AfterQuestions";

import StudyWord from 'components/PageCommon/StudyWord'

const { TabPane } = Tabs;
const {getPageJurisdiction,getStatusJurisdiction,statusValue} = commonConfig

// 主题课详情
const ThemeMain = forwardRef((props, ref) => {

  const {form,dictionaries,disabled,userName} = props

  const studyWord = useRef() //单词数据

  useImperativeHandle(ref, () => ({
    studyWord
  }));
  

  const themeItem = [
    {label: '课程名称',type:'input', name: 'lessonName',rules:[
      {
        required: true,
        message: '请输入课程名称'
      },
    ], span: 12 },
    {label: '级别', name: 'levelId', span: 12,rules:[
      {
        required: true,
        message: '请输入级别'
      },
    ],render: () => {
      return <Select
      allowClear
      disabled={disabled}
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择级别'}
      options={dictionaries.Level}
 >
 </Select> }},
    {label: '课程ID',type:'input', name: 'lessonCode', span: 12 },
    {label: '词汇',type:'textArea', name: 'words', span: 12 },
    {label: '课程目标',type:'textArea', name: 'remark', span: 12 },
    {label: '句型',type:'textArea', name: 'sentencePattern', span: 12 },
    {label: '拼读词汇',type:'textArea', name: 'lessonReading', span: 12 },
    {label: '字母',type:'textArea', name: 'letter', span: 12 },
    {label: '主题曲',type:'textArea', name: 'themeAudio', span: 12 },
    {label: '课程封面', name: 'pictureUrl', span: 13,render:()=>{
      return  <UploadPicture  disabled={true} pictureUrl={form.getFieldValue().pictureUrl} setPhoto={(value)=>form.setFieldsValue({...form.getFieldValue(),pictureUrl:value})}></UploadPicture>
    }},
  ]

  return <div  className='info-main'>
    <Tabs defaultActiveKey="1" tabPosition={'left'}>
    <TabPane tab="基本信息" key="1">
     <LlxForm disabled={disabled} form={form} labelCol={5} formItem={themeItem} />
    </TabPane>
    <TabPane tab="单词学习" key="2">
      <StudyWord typeName={'wordList'} ref={studyWord} disabled={disabled} dictionaries={dictionaries} form={form} userName={userName}></StudyWord>
    </TabPane>
    <TabPane tab="课后题" key="4">
    <AfterQuestions disabled={disabled} type={'THEME'} globalType={5} id={form.getFieldValue().id}></AfterQuestions>
    </TabPane>
  </Tabs>

  </div>
})
// 保存数据
const DataDialog  = (props) => {
  const {isModalVisible, setIsModalVisible,form,changeStatus,UserSpecies,userName,disabled,QandPQ} = props
  const value = statusValue(changeStatus,form.getFieldValue().lessonStatus) //修改的状态

  const loading = useRef(false)

  const manager = value==='Q'||value==='PQ'?QandPQ:UserSpecies

  const [formItem] = Form.useForm();//主题课详情

  const item = ['N','PN','P'].includes(value)?[
    {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
  ]:[
    {label: '负责人', name: 'manager' , span: 24 ,rules:[
      {
        required: true,
        message: '请选择负责人'
      },
    ],render:()=>{
      return  <Select

      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'userName',label:'userName'}}
      placeholder={'请选择负责人'}
      options={manager}
    >
    </Select>
    }},
    {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
  ]
  
 const handleCancel = () => {
    setIsModalVisible(false);
 };
 
 const handleOk = () => {
   if(loading.current) {
    message.error('请勿多次点击')
   }

  loading.current=true
  formItem.validateFields().then(async()=>{
  //  1更改状态
  await SubjectApprovalCourse({
    id: form.getFieldValue().id,
    lessonStatus: value,
    qmanager: value==='Q'||value==='PQ'?formItem.getFieldValue().manager:'',
    rmanager: value==='R'||value==='PR'?formItem.getFieldValue().manager:'',
  })
   
  // 留言
  await setRemark({
    manager: formItem.getFieldValue().manager||'',
    dataId: form.getFieldValue().id,
    type: 'LESSON',
    remark: formItem.getFieldValue().remark,
    statusNow: form.getFieldValue().lessonStatus,
    statusNext: value
  })

  //  2修改数据
   if(!disabled){
   
      const data =  form.getFieldValue()

      delete data.lessonStatus
      delete data.qmanager
      delete data.rmanager
      delete data.createBy
      delete data.lessonStatus
      delete data.updateTime
      data.lsLessonWordFlows = props.main.current.studyWord.current?props.main.current.studyWord.current.dataSource.map((i,j) => {
        return { flowLessonId: form.getFieldValue().id, id: i.id || '', wordId: i.wordId, picture: i.picture ,sort:j+1}
      }):form.getFieldValue().lessonWordFlows


        await AddOrModifyThemeCourses(data)

        notification.success({
          message: '保存成功',
          description: '操作人：' + userName,
          duration:1.5
        });
      
        props.getThemeInfoFn()
        formItem.resetFields()
        setIsModalVisible(false);
   } else {
    notification.success({
      message: '保存成功',
      description: '操作人：' + userName,
      duration:1.5
    });

    props.getThemeInfoFn()
    formItem.resetFields()
    setIsModalVisible(false);
   }
  })
  loading.current=false
 }

return   <>
<Modal onOk={handleOk}  width={600} title="保存数据" visible={isModalVisible}  onCancel={handleCancel}>
      <Alert className="edit-alert" message={'你确定要修改状态至' + value + '吗？'} type="success" />

     <LlxForm form={formItem} labelCol={3} formItem={item} />
 </Modal>
</>
}


function ThemeInfo(props) {

  const {examineStatus} = props
  const [isModalVisibleMore,setIsModalVisibleMore] = useState(false)
  const [isModalVisibleData,setIsModalVisibleData] = useState(false)
  const [disabled,setDisabled] = useState(false)
  const [loading,setLoading] = useState(true)
  const id = commonConfig.getUrlParams(props).id
  const [form] = Form.useForm();//主题课详情
  const head = useRef()
  const main = useRef()
  const [preservationJurisdiction,setPreservationJurisdiction] = useState({})
  // 1.获取数据
  useEffect(()=>{
    getThemeInfoFn()
  }, [examineStatus])// eslint-disable-line react-hooks/exhaustive-deps


  // 2.查看更多
  const getMore = () => {
    setIsModalVisibleMore(true)
  }
  // 3.保存数据
  const preservationData = () => {
   const value = statusValue(head.current.current,form.getFieldValue().lessonStatus)
   if(!getStatusJurisdiction(preservationJurisdiction[0],preservationJurisdiction[1],preservationJurisdiction[2],preservationJurisdiction[3],preservationJurisdiction[4],preservationJurisdiction[5]).includes(value)) {
    notification.error({
      message: '该数据你无法保存，请联系管理员',
      description: '操作人：' + props.userInfo.user.userName,
      duration:2
    });
    return
   }
  
  // 打开弹框 输入备注 修改状态 修改数据
  setIsModalVisibleData(true)


  }
  // 4.更新数据
  const getThemeInfoFn = async () => {
    if(examineStatus){
      const res = await getThemeByIdPublish(id)
      if(!res.result.id){
        notification.error({
          message: '该主题课未发布过',
          duration:1.5
        });
        props.checkDraftDataBtn()
        setLoading(false)
        return
      }
      form.setFieldsValue(res.result)
      form.setFieldsValue({
        wordList:res.result.lessonWords,
      })
      setDisabled(true)
  
      setLoading(false)
    } else {
      const res = await getThemeById(id)
      form.setFieldsValue(res.result)
      form.setFieldsValue({
        wordList:res.result.lessonWordFlows
      })

      setDisabled(!getPageJurisdiction(res.result.lessonStatus,res.result.createBy,props.userInfo.user.userName))

      setPreservationJurisdiction([res.result.lessonStatus,res.result.createBy,res.result.rmanager,res.result.qmanager,props.userInfo.user.userName,props.userInfo.roles.map(i => i.id).includes(7)])
     
      setLoading(false)
    }
  }

  return <div className="app-content-info animate__animated animate__fadeIn">
  {
    !loading?(
      <>
      <LlxHead nameType={'lessonName'} statusType={'lessonStatus'} examineStatus={examineStatus}  ref={head} preservationJurisdiction={preservationJurisdiction}  preservationData={preservationData} userName={props.userInfo.user.userName} role={props.userInfo.roles.map(i => i.id).includes(7)} form={form} getMore={getMore}></LlxHead>
       
       {/* 查看更多信息 */}
       <LookMore  type={'LESSON'} preservationJurisdiction={preservationJurisdiction}  isModalVisible={isModalVisibleMore}  setIsModalVisible={setIsModalVisibleMore} ></LookMore>
       {/* 保存数据 */}
       <DataDialog main={main} getThemeInfoFn={getThemeInfoFn}  form={form} QandPQ={props.dictionaries.QandPQ} UserSpecies={props.dictionaries.UserSpecies} userName={props.userInfo.user.userName} status={form} changeStatus={head.current?.current}   id={id} isModalVisible={isModalVisibleData} setIsModalVisible={setIsModalVisibleData} ></DataDialog>
       
       {/* 主要内容区域 */}
       {/* 1.草稿可编辑 */}
       <ThemeMain ref={main} form={form} userName={props.userInfo.user.userName} dictionaries={props.dictionaries} disabled={disabled}></ThemeMain>
      </>
    ):<Spin className="info-loading" tip="Loading..."></Spin>
  }
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    checkDraftDataBtn: () => dispatch(checkDraftData())
  }
}

export default connect((state)=>{
  return {examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(withRouter(ThemeInfo))